package edu.hunan.cxb18.controller;

import edu.hunan.cxb18.error.BaseController;
import edu.hunan.cxb18.error.impl.CommonErrorImpl;
import edu.hunan.cxb18.error.impl.UserException;
import edu.hunan.cxb18.pojo.User;
import edu.hunan.cxb18.result.CommonTypeResult;
import edu.hunan.cxb18.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @author AuthorName
 * @create 2020-04-22 15:57
 */
@RestController
@RequestMapping("/user")
public class UserController extends BaseController {
    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public CommonTypeResult test(@RequestBody User user,HttpServletRequest request) throws UserException {
        User login = userService.login(user);
        request.getSession().setAttribute("LOGIN",true);
        request.getSession().setAttribute("LOGIN_USER",login);
        return CommonTypeResult.creat(login);
    }

    @PostMapping("/register")
    public CommonTypeResult register(@RequestBody User user) throws UserException {
        userService.register(user);
        return CommonTypeResult.creat(null);
    }
    @GetMapping("/checkstatus")
    public CommonTypeResult checkstatus(HttpServletRequest request) {
        Object u = request.getSession().getAttribute("LOGIN_USER");
        if (u == null){
            return CommonTypeResult.creat(u,"false");
        }
        return CommonTypeResult.creat(u);
    }
    @GetMapping("/logout")
    public CommonTypeResult logout(HttpServletRequest request){
        request.getSession().removeAttribute("LOGIN_USER");
        request.getSession().removeAttribute("car");
        return CommonTypeResult.creat(null);
    }
}
